package _08_DFS_BFS;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _39_组合总和 {

    public static void main(String[] args) {
        _39_组合总和 v = new _39_组合总和();
        int[] ins = new int[]{1};
        List<List<Integer>> lists = v.combinationSum(ins, 2);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }

    private final List<List<Integer>> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // 数组排序，加快剪枝效率
        Arrays.sort(candidates);
        dfs(candidates, 0, target, new ArrayList<>());
        return list;
    }

    private void dfs(int[] candidates, int begin, int target, List<Integer> integers) {
        if (target == 0) {
            // 找到解
            list.add(new ArrayList<>(integers));
            return;
        }
        for (int i = begin; i < candidates.length; i++) {
            // 剪枝处理器
            if (target - candidates[i] < 0) break;
            integers.add(candidates[i]);
            dfs(candidates, i, target - candidates[i], integers);
            integers.remove(integers.size() - 1);
        }
    }

}
